<template>
  <div>
    <div :style="completeStyles"></div>
  </div>
</template>

<script lang="ts">
  import { Component, NoCache, Vue, Prop } from "@some21/vue-class-decorator";
  import dayjs from "dayjs";

  const defaultStaticStyles = {
    position: "fixed",
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    zIndex: 99999,
    pointerEvents: "none", // 使得可以点击图片穿透
  };
  const fontSize = 18;
  const angle = -30;
  @Component({
    name: "water-mark",
  })
  export default class extends Vue {
    staticStyles: any = {
      background: "none",
    };
    padding = 20;
    width = 300;
    height = 200;
    color = "rgba(170, 170, 170,0.75)";

    @Prop({ type: Array, required: true })
    text: string[];
    // text = [UserModule.CompanyName, UserModule.UserName + "@" + UserModule.CompanyCode];

    @NoCache
    get completeStyles() {
      return { ...this.staticStyles, ...defaultStaticStyles };
    }

    timer: number;

    refreshWater() {
      const canvasElm = document.createElement("canvas");
      const ctx = canvasElm.getContext("2d");
      const textAngle = (angle * Math.PI) / 180;

      canvasElm.width = this.width;
      canvasElm.height = this.height;
      const contentWidth = this.width - 2 * this.padding; // 有效宽度
      // 清空画布
      ctx.clearRect(0, 0, this.width, this.height);
      ctx.globalAlpha = 0.3; // 透明度 0-1
      ctx.translate((this.width / 4) * 3, 0); // 设置起始点
      ctx.rotate(textAngle); // 旋转画布
      ctx.translate((-this.width / 4) * 3, 0); // 还原起始点

      //#region 预设水印样式
      ctx.textBaseline = "top";
      ctx.textAlign = "center";
      ctx.fillStyle = this.color;
      ctx.font = `${fontSize}px/1.1em 黑体`;
      //#endregion

      const x = this.width / 3;
      let y = 0; // 因为存在旋转因子，所以此起始绘制位置不需要为padding
      this.text.forEach(text => {
        let lineWidth = 0;
        let lastSubStrIndex = 0;
        // 绘制文字，自动换行
        for (let i = 0; i < text.length; i++) {
          const { width } = ctx.measureText(text[i]);
          lineWidth += width;
          if (lineWidth > contentWidth) {
            const metrics = ctx.measureText(text.substring(lastSubStrIndex, i));
            // 减去initX,防止边界出现的问题
            ctx.fillText(text.substring(lastSubStrIndex, i), x, y, contentWidth);
            y += metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent; // 加上文字高度

            lineWidth = 0;
            lastSubStrIndex = i;
          }
          if (i === text.length - 1) {
            const metrics = ctx.measureText(text.substring(lastSubStrIndex, i));
            ctx.fillText(text.substring(lastSubStrIndex, i + 1), x, y, contentWidth);
            y += metrics.fontBoundingBoxAscent + metrics.fontBoundingBoxDescent; // 加上文字高度
          }
        }

        // 测算刚才绘制内容所占区域高度，同时可以移动坐标绘制下一个绘制对象的开始位置
      });

      ctx.textBaseline = "top";
      ctx.textAlign = "center";
      ctx.fillStyle = this.color;
      ctx.font = `14px timesnewroman`;
      const time = dayjs().format("YYYY-M-D HH:mm");
      ctx.fillText(time, x, y, contentWidth);

      this.staticStyles.background = `url(${canvasElm.toDataURL()}) !important`;
    }
    loopRender() {
      this.refreshWater();
      // 重绘
      this.timer = requestAnimationFrame(this.loopRender);
    }

    mounted() {
      this.loopRender();
    }

    beforeDestroy() {
      if (this.timer) {
        cancelAnimationFrame(this.timer);
      }
    }
  }
</script>


